<template>
  <Dropdown placement="bottomLeft" :overlayClassName="`${prefixCls}-dropdown-overlay`">
    <span :class="[prefixCls, `${prefixCls}--${theme}`]" class="flex">
      <img :class="`${prefixCls}__header`" :src="getUserInfo.avatar" />
      <span :class="`${prefixCls}__info hidden md:block`">
        <span :class="`${prefixCls}__name`" class="truncate">
          {{ getUserInfo.username }}（{{ getUserInfo.role_name }}）
        </span>
      </span>
    </span>

    <template #overlay>
      <Menu @click="handleMenuClick">
        <MenuItem
          key="doc"
          :text="t('layout.header.dropdownItemDoc')"
          icon="ion:document-text-outline"
          v-if="getShowDoc"
        />
        <Menu.Divider v-if="getShowDoc" />
        <MenuItem key="setPassword" text="修改密码" icon="material-symbols:edit-outline" />
        <MenuItem
          v-if="getShowApi"
          key="api"
          :text="t('layout.header.dropdownChangeApi')"
          icon="ant-design:swap-outlined"
        />
        <MenuItem
          v-if="getUseLockPage"
          key="lock"
          :text="t('layout.header.tooltipLock')"
          icon="ion:lock-closed-outline"
        />
        <MenuItem
          key="logout"
          :text="t('layout.header.dropdownItemLoginOut')"
          icon="ion:power-outline"
        />
      </Menu>
    </template>
  </Dropdown>
  <LockAction @register="register" />
  <ChangeApi @register="registerApi" />
  <BasicModal
    @register="registeUpdateModal"
    title="修改密码"
    @ok="fnBtnModalSubmit"
    @cancel="fnBtnModalCancel"
  >
    <BasicForm @register="registerModalForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { Dropdown, Menu } from 'ant-design-vue';
  import type { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
  import { computed } from 'vue';
  import { DOC_URL } from '@/settings/siteSetting';
  import { useUserStore } from '@/store/modules/user';
  import { useHeaderSetting } from '@/hooks/setting/useHeaderSetting';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useDesign } from '@/hooks/web/useDesign';
  import { useModal } from '@/components/Modal';
  import headerImg from '@/assets/images/header.jpg';
  import { propTypes } from '@/utils/propTypes';
  import { openWindow } from '@/utils';
  import { createAsyncComponent } from '@/utils/factory/createAsyncComponent';
  import BasicModal from '@/components/Modal/src/BasicModal.vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { FormSchema } from '@/components/Form';
  import { encryptByMd5 } from '@/utils/cipher';
  import { apiEditUserPassword } from '@/api/sys/user';

  type MenuEvent = 'logout' | 'doc' | 'lock' | 'api' | 'setPassword';

  const MenuItem = createAsyncComponent(() => import('./DropMenuItem.vue'));
  const LockAction = createAsyncComponent(() => import('../lock/LockModal.vue'));
  const ChangeApi = createAsyncComponent(() => import('../ChangeApi/index.vue'));

  defineOptions({ name: 'UserDropdown' });

  defineProps({
    theme: propTypes.oneOf(['dark', 'light']),
  });

  const { prefixCls } = useDesign('header-user-dropdown');
  const { t } = useI18n();
  const { getShowDoc, getUseLockPage, getShowApi } = useHeaderSetting();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    const { username, avatar, desc, role_name } = userStore.getUserInfo || {};
    return { username, avatar: avatar || headerImg, desc, role_name };
  });

  const { createMessage, createConfirm } = useMessage();

  const schemas: FormSchema[] = [
    {
      field: 'old',
      label: '旧密码',
      required: true,
      component: 'InputPassword',
      componentProps: {
        placeholder: '请输入旧密码',
        onkeydown: (e) => {
          if (e.key == ' ') {
            e.preventDefault();
          }
        },
      },
      rules: [
        {
          // @ts-ignore
          validator: async (rule, value) => {
            if (!value) {
              return Promise.reject('');
            }
          },
        },
      ],
    },
    {
      field: 'new',
      label: '新密码',
      required: true,
      component: 'InputPassword',
      componentProps: {
        placeholder: '请输入新密码',
        onkeydown: (e) => {
          if (e.key == ' ') {
            e.preventDefault();
          }
        },
      },
      rules: [
        {
          // @ts-ignore
          validator: async (rule, value) => {
            if (!value) {
              return Promise.reject('');
            }
            if (value.length < 6) {
              return Promise.reject('密码长度必须大于6');
            }
            if (value.length > 16) {
              return Promise.reject('密码长度必须小于16');
            }
            return Promise.resolve();
          },
        },
      ],
    },
    {
      field: 'confirm',
      label: '确认新密码',
      required: true,
      component: 'InputPassword',
      componentProps: {
        placeholder: '请确认新密码',
        onkeydown: (e) => {
          if (e.key == ' ') {
            e.preventDefault();
          }
        },
      },
      dynamicRules: ({ values }) => {
        return [
          {
            required: true,
            validator: (_, value) => {
              if (!value) {
                return Promise.reject('密码不能为空');
              }
              if (value !== values.new) {
                return Promise.reject('两次输入的密码不一致!');
              }
              return Promise.resolve();
            },
          },
        ];
      },
    },
  ];
  const [register, { openModal }] = useModal();
  const [registerApi, { openModal: openApiModal }] = useModal();
  const [registeUpdateModal, { openModal: openUpdateModal, closeModal: closeUpdateModal }] =
    useModal();
  function handleLock() {
    openModal(true);
  }

  function handleApi() {
    openApiModal(true, {});
  }

  //  login out
  function handleLoginOut() {
    userStore.confirmLoginOut();
  }

  // open doc
  function openDoc() {
    openWindow(DOC_URL);
  }

  function handleMenuClick(e: MenuInfo) {
    switch (e.key as MenuEvent) {
      case 'logout':
        handleLoginOut();
        break;
      case 'doc':
        openDoc();
        break;
      case 'lock':
        handleLock();
        break;
      case 'api':
        handleApi();
        break;
      case 'setPassword':
        handleSetPassword();
        break;
    }
  }
  const [registerModalForm, { resetFields, validate }] = useForm({
    labelAlign: 'left',
    baseColProps: { span: 22 },
    labelCol: {
      style: {
        marginLeft: '40px',
        width: '100px',
      },
    },
    schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });

  async function fnBtnModalSubmit() {
    let valueData = await validate();
    if (valueData.new !== valueData.confirm) {
      createMessage.error('两次输入的新密码不一致');
      return;
    }
    console.log(getUserInfo.value);
    createConfirm({
      iconType: 'warning',
      title: () => '提示',
      content: () => '确认修改密码吗',
      onOk: async () => {
        await apiEditUserPassword({
          old: encryptByMd5(valueData.old),
          new: encryptByMd5(valueData.new),
          username: getUserInfo.value.username,
        });
        fnBtnModalCancel();
        createMessage.success('修改密码成功,请重新登录');
        await setTimeout(() => {
          userStore.logout();
        }, 1000);
      },
    });
  }
  function handleSetPassword() {
    openUpdateModal();
  }
  function fnBtnModalCancel() {
    closeUpdateModal();
    resetFields();
  }
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-user-dropdown';

  .@{prefix-cls} {
    align-items: center;
    height: @header-height;
    padding: 0 0 0 10px;
    padding-right: 10px;
    overflow: hidden;
    font-size: 12px;
    cursor: pointer;

    img {
      width: 24px;
      height: 24px;
      margin-right: 12px;
    }

    &__header {
      border-radius: 50%;
    }

    &__name {
      font-size: 14px;
    }

    &--dark {
      &:hover {
        background-color: @header-dark-bg-hover-color;
      }
    }

    &--light {
      &:hover {
        background-color: @header-light-bg-hover-color;
      }

      .@{prefix-cls}__name {
        color: @text-color-base;
      }

      .@{prefix-cls}__desc {
        color: @header-light-desc-color;
      }
    }

    &-dropdown-overlay {
      .ant-dropdown-menu-item {
        min-width: 160px;
      }
    }
  }
</style>
